package com.baayso.bms2.config.spring;

import javax.inject.Inject;
import javax.persistence.EntityManagerFactory;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.alibaba.druid.pool.DruidDataSource;

/**
 * JPA配置。
 * 
 * @author ChenFangjie(2015年9月19日 下午9:31:11)
 * 
 * @since 1.0.0
 * 
 * @version 1.0.0
 * 
 */
@Configuration
@EnableJpaRepositories(basePackages = "com.baayso.bms2")
// @EnableTransactionManagement
@EnableTransactionManagement(proxyTargetClass = true) // 启用注解事务管理，使用CGLib代理
@Import({ DataSourceConfig.class })
public class JpaConfig {

    // private static final Logger log = Log.get();

    @Inject
    private DruidDataSource druidDataSource;

    // @Bean
    // public DataSource dataSource() {
    // EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
    // return builder.setType(EmbeddedDatabaseType.HSQL).build();
    // }

    @Bean
    public EntityManagerFactory entityManagerFactory() {
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setGenerateDdl(true);

        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setJpaVendorAdapter(vendorAdapter);
        factory.setPackagesToScan("com.baayso.bms2");
        factory.setDataSource(this.druidDataSource);
        factory.afterPropertiesSet();

        return factory.getObject();
    }

    @Bean
    public PlatformTransactionManager transactionManager() {
        JpaTransactionManager txManager = new JpaTransactionManager();
        txManager.setEntityManagerFactory(this.entityManagerFactory());

        return txManager;
    }

}
